<?php
namespace app\admin\controller;

use app\BaseController;
use think\facade\View;
use think\captcha\facade\Captcha;
use app\admin\model\sys\Admin;
use app\admin\model\sys\AuthGroup;
use \think\facade\Request;

class Login extends BaseController {
    public function index()
    {
        if ($this->request->isPost()) {
            $username = $this->request->post('username', '', '');
            $password = $this->request->post('password', '', '');
            $verify = $this->request->post('vercode', '', '');
            // 用户信息验证
            try {
                if(!captcha_check($verify)){
                    throw new \Exception('验证码错误');
                }
                $data['username'] = $username;
                $data['password']  = $password;
                $res = $this->checkLogin($data);
            } catch (\Exception $e) {
                $this->error("登陆失败：{$e->getMessage()}");
            }
            $this->success('登录成功，正在进入系统...', url('admin/Index/index'));
        }
        return View::fetch();
    }

    /*验证码*/
    public function Verify()
    {
        return Captcha::create('verify');
    }

    /*验证登录*/
    public function checkLogin($data){
        $username = trim($data['username']);
        $user=Admin::where('username',$username)->find();

        if(!$user) {
            throw new \Exception("用户不存在");
        }
        if ($user['status']==0 ) {
            throw new \Exception("该账户被禁用");
        }
        if (!password_verify($data['password'], $user['password'])) {
            throw new \Exception('密码不正确');
        }
        Admin::where('username',$username)->update(['lastlogintime' => time(),'ip'=>Request::ip()]);
        $userInfo = [
            'username' => $user['username'],
            'id' => $user['id'],
            'group_id' => $user['group_id'],
        ];
        session('admin', $userInfo, 72*86400);
        return true;     
    }
}